package com.bto.solar.work.service.biz_stage_handler;

import com.alibaba.fastjson2.JSONArray;
import com.bto.solar.work.common.BizException;
import com.bto.solar.work.constant.BizStageEnum;
import com.bto.solar.work.constant.BizTaskEnum;
import com.bto.solar.work.constant.BizTaskStateEnum;
import com.bto.solar.work.constant.Constants;
import com.bto.solar.work.dao.IConstructService;
import com.bto.solar.work.dao.IOrderBaseService;
import com.bto.solar.work.dao.IRecordService;
import com.bto.solar.work.entity.Construct;
import com.bto.solar.work.entity.OrderBase;
import com.bto.solar.work.entity.Record;
import com.bto.solar.work.entity.User;
import com.bto.solar.work.service.BtoOrderStateService;
import com.bto.solar.work.service.BtoUserService;
import com.bto.solar.work.utils.NullUtils;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Component
public class BeiAnZhengXingxiHandler  implements StageHandler {

    @Autowired
    private BtoOrderStateService btoOrderStateService;
    @Autowired
    private BtoUserService btoUserService;
    @Autowired
    private IRecordService recordService;
    @Autowired
    private IConstructService constructService;
    @Autowired
    private IOrderBaseService orderBaseService;
    @Autowired
    private ShiGongStageHandler shiGongStageHandler;

    @Autowired
    private RedissonClient redissonClient;

    private final String takId = BizTaskEnum.TASK_BAZXX.getTaskId();

    @Override
    //备案证阶段初始化--备案证信息任务--待填写
    public void createNewInitState (String orderId, String stageId, String taskId) {
        btoOrderStateService.createOrderState(orderId, BizStageEnum.BAZING.getStageId(), this.takId,
                BizTaskStateEnum.WAITING_FILLED.getStateId());
    }

    //备案证阶段待审核--备案证信息任务（前置条件：待填写、博通审核拒绝、越秀审核拒绝）  备案整提交审批-状态变为填写OK
    @Override
    public void updateToWaitingApprovalState (String orderId, String stageId, String taskId) {
        btoOrderStateService.updateOrSaveOrderState(orderId, BizStageEnum.BAZING.getStageId(), BizTaskEnum.TASK_BAZXX.getTaskId(),
                BizTaskStateEnum.FILLED_OK.getStateId(),
                BizTaskStateEnum.FILLED_OK.getStateId(),
                BizTaskStateEnum.WAITING_FILLED.getStateId(),
                BizTaskStateEnum.APPROVAL_REJECT_BTO.getStateId(),
                BizTaskStateEnum.APPROVAL_REJECT_LEASE.getStateId());
    }

    @Override
    public void updateToApprovalPassState (String orderId, String stageId, String taskId, String approvalType) {
        if (Constants.APPROVAL_BTO.equals(approvalType)) {
            // 备案证信息博通待审核 --》 博通审核通过
            btoOrderStateService.updateOrSaveOrderState(orderId, BizStageEnum.BAZING.getStageId(), BizTaskEnum.TASK_BAZXX.getTaskId(),
                    BizTaskStateEnum.APPROVAL_PASS_BTO.getStateId(),
                    BizTaskStateEnum.WAITING_APPROVAL_BTO.getStateId(), true);
            // 博通审核（施工阶段的任务和备案证信息）全部通过 --> 越秀待审核
            shiGongStageHandler.updateApprovalAllPassStateBySgAndBaz(orderId);
        }
//        else if(Constants.APPROVAL_LEASE.equals(approvalType)){
//            // 备案证信息越秀待审核 --》 越秀审核通过
//            btoOrderStateService.updateOrSaveOrderState(orderId, BizStageEnum.BAZING.getStageId(), BizTaskEnum.TASK_BAZXX.getTaskId(),
//                    BizTaskStateEnum.APPROVAL_PASS_LEASE.getStateId(),
//                    BizTaskStateEnum.WAITING_APPROVAL_LEASE.getStateId(), true);
//            //检查施工信息和备案证信息是否越秀审核全部通过
//            if (shiGongStageHandler.checkAllConstructInfoState(orderId , BizTaskStateEnum.APPROVAL_PASS_LEASE.getStateId())) {
//                //开启并网阶段
//                bingWangStageHandler.createNewInitState(orderId, BizStageEnum.GRID_CONNECTION.getStageId(), null);
//            }
//        }
    }

    @Override
    public void updateToApprovalRejectState(String orderId, String stageId, String taskId, String approvalType , Object rejectInfo) {
        //博通审核 备案证信息博通待审核 --》 博通审核拒绝
        if(Constants.APPROVAL_BTO.equals(approvalType)){
            btoOrderStateService.updateOrSaveOrderState(orderId, BizStageEnum.BAZING.getStageId(), BizTaskEnum.TASK_BAZXX.getTaskId(),
                    BizTaskStateEnum.APPROVAL_REJECT_BTO.getStateId(),
                    BizTaskStateEnum.WAITING_APPROVAL_BTO.getStateId(), true);
        }
        //越秀审核  备案证信息博通审核通过 --> 越秀审核拒绝
        else if(Constants.APPROVAL_LEASE.equals(approvalType)){
            btoOrderStateService.updateOrSaveOrderState(orderId, BizStageEnum.BAZING.getStageId(), BizTaskEnum.TASK_BAZXX.getTaskId(),
                    BizTaskStateEnum.APPROVAL_REJECT_LEASE.getStateId(),
                    BizTaskStateEnum.APPROVAL_PASS_BTO.getStateId(), true);
        }
    }

    /**
    * 备案证容量，
     * 提交审批时。计算更新
     * 拒绝时，返回容量
    */
    private void updateRecordCapacity(String orderId  , String type){
        //加锁
        RLock lock = redissonClient.getLock(Constants.ORDER_LOCK+orderId);
        boolean tryLock = false;
        try {
            tryLock = lock.tryLock(2 , 2 , TimeUnit.SECONDS);
            if(tryLock){
                OrderBase orderBase = orderBaseService.getById(orderId);
                Record record = recordService.getById(orderBase.getRecordCertificateId());
                User curUser = btoUserService.getCurrentUser();
                Construct construct = constructService.getById(orderId);
                //大备案证容量结算
                if (1 == record.getRecordType() && NullUtils.isNotNull(construct)) {
                    int surplusCapacity = Optional.ofNullable(record.getSurplusCapacity()).orElse(record.getRecordCertificateCapacity());

                    if (NullUtils.isNotNull(construct.getInstalledCapacityReality())) {
                        //占用容量
                        if("USED".equals(type)){
                            surplusCapacity = record.getSurplusCapacity() - construct.getInstalledCapacityReality();
                            if (surplusCapacity < 0) {
                                throw new BizException("该备案证剩余容量 不足 {}", construct.getInstalledCapacityReality());
                            }
                            //新增备案证关联公司
                            List<Long> companyIds = JSONArray.parseArray(record.getAccreditCompanyIds(), Long.class);
                            if (companyIds.contains(curUser.getCompanyId())) {
                                companyIds.add(curUser.getCompanyId());
                                companyIds = companyIds.stream().distinct().collect(Collectors.toList());
                                record.setAccreditCompanyIds(JSONArray.toJSONString(companyIds));
                            }
                        }
                        //返回容量
                        else if("RETURN".equals(type)){
                            surplusCapacity = record.getSurplusCapacity() + construct.getInstalledCapacityReality();
                            //移除备案证关联公司
                            List<Long> companyIds = JSONArray.parseArray(record.getAccreditCompanyIds(), Long.class);
                            if (companyIds.contains(curUser.getCompanyId())) {
                                companyIds.remove(curUser.getCompanyId());
                                companyIds = companyIds.stream().distinct().collect(Collectors.toList());
                                record.setAccreditCompanyIds(JSONArray.toJSONString(companyIds));
                            }
                        }
                    }
                    record.setSurplusCapacity(surplusCapacity);
                    recordService.updateById(record);
                }
            }
            else {
                throw new BizException("订单 {} 备案证，容量更新加锁失败");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        finally {
            if(tryLock){
                lock.unlock();
            }
        }


    }




}
